package pers.xx.sbm.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import pers.xx.sbm.dao.MenuMapper;
import pers.xx.sbm.dao.MenuRoleMapper;
import pers.xx.sbm.entity.Menu;
import pers.xx.sbm.entity.MenuRole;
import pers.xx.sbm.entity.User;
import pers.xx.sbm.enums.ResultEnum;
import pers.xx.sbm.service.MenuRoleService;
import pers.xx.sbm.utils.UserUtils;
import pers.xx.sbm.vo.ResResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ：xiexing
 * @description：菜单角色接口实现类
 * @date ：2020/9/15 21:06
 */
@Service
public class MenuRoleServiceImpl extends BaseServiceImpl implements MenuRoleService {
    MenuRoleMapper menuRoleMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    private UserUtils userUtils;

    public MenuRoleServiceImpl(@Autowired MenuRoleMapper menuRoleMapper) {
        this.menuRoleMapper = menuRoleMapper;
        super.dao = menuRoleMapper;
    }

    @Override
    public ResResult insertBatch(Integer roleId, String menus) {
        if (menus == null) {
            return new ResResult(ResultEnum.PARAM_ERR, "菜单参数不能为空");
        }
        menuRoleMapper.deleteByRoleId(roleId);//现根据角色id删除相关数据
        String[] menuIdArr = menus.split(",");
        if (menuIdArr.length == 1 && menuIdArr[0].equals("")) {//不授权任何菜单
            return new ResResult(ResultEnum.SUCCESS, "授权成功");
        }
        List<MenuRole> menuRoles = new ArrayList<>();
        User user = userUtils.getCurrentUser();
        for (String menuId : menuIdArr) {
            MenuRole menuRole = new MenuRole();
            menuRole.setMenuId(Integer.valueOf(menuId));//设置菜单id
            menuRole.setRoleId(Integer.valueOf(roleId));//设置角色id

            menuRole.setMenuRoleAdderId(user.getId());//添加人id
            menuRole.setMenuRoleAdder(user.getUserName());//添加人姓名
            menuRole.setMenuRoleAdderTime(new Date());
            menuRoles.add(menuRole);
        }
        menuRoleMapper.insertBatch(menuRoles);
        reloadMenu(user.getId());//更新redis缓存
        return new ResResult(ResultEnum.SUCCESS, "授权成功");
    }


    /**
     * @description 菜单更新 更新redis缓存
     * @author XieXing
     * @date 2020/12/9 11:20
     */
    private void reloadMenu(Integer userId) {
        ValueOperations<String, List<Menu>> valueOperations = redisTemplate.opsForValue();
        List<Menu> menus = menuMapper.getMenuByUserId(userId);
        valueOperations.set("menus", menus);
    }

}
